package com.sxj.corejava.code09_集合;

import java.util.*;
import java.util.Map.Entry;


/**
 * @author 石小俊
 * @date 2024年05月09日 19:41
 */
public class Test02_练习 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("请输入一个字符串:");
        String s = sc.next();
        Map<Character, Integer> map = new HashMap<>();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            map.put(c, map.containsKey(c) ? map.get(c) + 1 : 1);
        }

        Set<Entry<Character, Integer>> set = map.entrySet();
        List<Entry<Character, Integer>> list = new ArrayList<>(set);
        Collections.sort(list, new Comparator<Entry<Character, Integer>>() {
            @Override
            public int compare(Entry<Character, Integer> o1, Entry<Character, Integer> o2) {
                if (o1.getValue() > o2.getValue()) {
                    return -1;
                } else if (o1.getValue() < o2.getValue()) {
                    return 1;
                }
                return 0;
            }
        });

        System.out.println(list);
        System.out.println("出现次数最多的前三个字符以及其出现的次数如下:");
        for (int i = 0; i < 3; i++) {
            Entry<Character, Integer> entry = list.get(i);
            System.out.println("字符" + entry.getKey() + "出现的次数为:" + entry.getValue());
        }
    }

}
